package yanglib.network;

import yanglib.membership.Membership;
import yanglib.message.Message;
import yanglib.message.MessageDeserializer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 9/4/14
 * Time: 7:37 PM
 * To change this template use File | Settings | File Templates.
 */
public abstract class Network {

    protected Membership membership;
    protected MessageHandler msgHandler;
    protected MessageDeserializer msgDeserializer;
    protected int selfID;
    protected final int maxBufferSize = 1024 * 1024;
    private byte[] sendingBytes = new byte[maxBufferSize];
    ByteBuffer sendingBuffer = ByteBuffer.wrap(sendingBytes);

    public Network(Membership membership, MessageHandler msgHandler, MessageDeserializer msgDeserializer, int selfID){
        this.membership = membership;
        this.msgHandler = msgHandler;
        this.msgDeserializer = msgDeserializer;
        this.selfID = selfID;
    }

    protected abstract void send(byte[] bytes, int offset, int len, InetSocketAddress target) throws IOException;

    public synchronized void send(Message message, int target) throws IOException{
        sendingBuffer.clear();

        sendingBuffer.putInt(0); //place holder for length
        message.serialize(sendingBuffer);
        int size = sendingBuffer.position() - 4;
        sendingBuffer.flip();
        sendingBuffer.putInt(size);
        this.send(sendingBytes, 0, size+4, membership.getAddress(target));
    }

}
